package easy.trace.plugin.springmvc.define;

import easy.trace.agent.define.Instrumentation;
import easy.trace.core.util.StringUtils;
import javassist.*;

/**
 * @author easy
 */
public class SpringMvcInstrumentation implements Instrumentation {
    private static final String ENHANCE_TRANSFORM_CLASS = "org/springframework/web/servlet/handler/AbstractHandlerMapping";
    private static final String ENHANCE_CLASS = "org.springframework.web.servlet.handler.AbstractHandlerMapping";
    private static final String ENHANCE_METHOD = "initInterceptors";

    @Override
    public byte[] interceptPoints() {
        System.out.println("---------------transform :" + ENHANCE_CLASS + " start---------------");
        try {
            ClassPool classPool = ClassPool.getDefault();
            CtClass ctClass = classPool.getCtClass(ENHANCE_CLASS);

            CtMethod execute = ctClass.getDeclaredMethod(ENHANCE_METHOD);
            execute.insertBefore("this.adaptedInterceptors.add(new easy.trace.plugin.springmvc.SpringMvcInterceptor());");
            System.out.println("---------------transform :" + ENHANCE_CLASS + " end---------------");
            return ctClass.toBytecode();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new byte[0];
    }

    @Override
    public String getInterceptClass() {
        return ENHANCE_TRANSFORM_CLASS;
    }

    @Override
    public boolean check(String className) {
        if (StringUtils.isEmpty(className)) {
            return false;
        }
        if (className.length() == 0) {
            return false;
        }
        if (ENHANCE_TRANSFORM_CLASS.equalsIgnoreCase(className)) {
            return true;
        }
        return false;
    }
}
